<template>
  <!--  待办-->
  <!--    <up-subsection :current="1" :list="list" activeColor="#f56c6c" fontSize="15"-->
  <!--                   inactiveColor="#303133"></up-subsection>-->
  <uni-section title="待办事项" type="line">
    <view class="uni-padding-wrap uni-common-mt">
      <uni-segmented-control :active-color="activeColor" :current="current" :style-type="styleType"
                             :values="items" @clickItem="onClickItem"/>
    </view>
    <view class="content">
      <template v-if="arrOne.length === 0">
        <up-empty
            icon="http://cdn.uviewui.com/uview/empty/list.png"
            mode="list"
        ></up-empty>
      </template>
      <template v-else>
        <uni-list :border="true">
          <uni-swipe-action v-for="(item,index) in arrOne" :key="index">
            <uni-transition ref="ani" :mode-class="modeClass"
                            :show="item.shows" :styles="styless"
                            custom-class="transition">
              <uni-swipe-action-item :right-options="options" auto-close="true"
                                     @click="(e)=>oncl(e,item,index)">
                <!-- 显示圆形头像 -->
                <uni-list-chat :avatar="item.avatar"
                               :avatar-circle="true"
                               :note="item.content"
                               :time="item.createTime" :title="item.title" clickable @click="onClickChat(item)">
                  <view class="chat-custom-right">
                    <uni-dateformat :date="item.createTime" :threshold="[60000, 3600000]" class="chat-custom-text"
                                    locale="zh"></uni-dateformat>
                  </view>
                </uni-list-chat>
              </uni-swipe-action-item>
            </uni-transition>
          </uni-swipe-action>
        </uni-list>
      </template>
    </view>
  </uni-section>
  <up-popup :round="10" :show="showT" mode="bottom" @close="close" @open="open">
    <uni-section title="代办详情" type="line">
      <!-- 基础用法，不包含校验规则 -->
      <uni-forms ref="baseForm" :modelValue="formValues">
        <uni-forms-item label="代办标题" name="title">
          <uni-easyinput v-model="formValues.title" :disabled="formValues.status === 3"
                         placeholder="请输入代办标题"/>
        </uni-forms-item>
        <uni-forms-item label="代办内容" name="content">
          <uni-easyinput v-model="formValues.content" :disabled="formValues.status === 3" autoHeight
                         placeholder="请输入代办内容"
                         type="textarea"/>
        </uni-forms-item>
        <uni-forms-item label="预期时间" name="expectedTime">
          <uni-datetime-picker v-model="formValues.expectedTime" :disabled="formValues.status === 3"
                               return-type="datetime"
                               type="datetime"/>
        </uni-forms-item>
        <uni-forms-item label="代办地点" name="location">
          <uni-easyinput v-model="formValues.location" :disabled="formValues.status === 3"
                         placeholder="请输入代办地点"/>
        </uni-forms-item>
        <uni-forms-item label="优先级" name="taskPriority">
          <uni-data-select v-model="formValues.taskPriority" :disabled="formValues.status === 3" :localdata="range"
          />
        </uni-forms-item>
      </uni-forms>
      <up-button
          :disabled="formValues.status === 3"
          customStyle="margin-top: 50px"
          text="提交"
          type="primary"
          @click="submit"
      ></up-button>
      <up-button
          :disabled="formValues.status === 3"
          customStyle="margin-top: 10px"
          text="重置"
          type="error"
          @click="reset"
      ></up-button>
    </uni-section>
  </up-popup>
  <!--悬浮按钮-->
  <uni-fab
      :pattern="pattern"
      horizontal="right"
      popMenu="false"
      @fabClick="fabClick"
  ></uni-fab>
  <up-toast ref="uToastRef" style="z-index: 10176"></up-toast>
</template>

<script setup>
import {reactive, ref} from 'vue';
import {deleteDaiBanAPI, getDaiBanAPI, updateDaiBanAPI, updateDaiBanOneAPI} from '../../api/daiban.js'
import {onShow} from "@dcloudio/uni-app";
/*优先级数据*/
const range = ref([
  {value: 1, text: "优先级1"},
  {value: 2, text: "优先级2"},
  {value: 3, text: "优先级3"},
]);
/*悬浮按钮*/
const pattern = ref({
  color: '#7A7E83',
  backgroundColor: '#fff',
  selectedColor: '#007AFF',
  buttonColor: '#007AFF',
  iconColor: '#fff'
})
const curNow = ref(0);
const listData = ref([]);
const items = ref(['进行中', '未开始', '已完成', '逾期'])
const styles = ref([]);
const colors = ref(['#007aff', '#4cd964', '#dd524d'])
const current = ref(0)
const colorIndex = ref(0)
const activeColor = ref('#007aff')
const styleType = ref('button')
const show = ref(false)
const modeClass = ref()
const styless = ref();
const type = ref('center')
const ind = ref(0)
const showBirthday = ref(false)
// 创建响应式数据
const showT = ref(false);
const inputDialog = ref(null)

const onClickItem = async (e) => {
  arrOne.value = [];
  arrOne.value = await fetchData(e.currentIndex + 1);
}

/*点击+号的操作*/
const fabClick = () => {
  console.log('fabClick')
  reset();
  delete formValues.value.id
  formValues.value.flagNew = true;
  showT.value = true
}
const open = () => {
  showT.value = true
}

/*点击列表 显示修改框*/
const onClickChat = async (item) => {
  daibaninfo.value = item
  formValues.value = {...daibaninfo.value};
  formValues.value.flagNew = false;
  showT.value = true
}
/*点击空白取消显示修改框*/
const close = () => {
  formValues.value.flagNew = false;
  showT.value = false
}


// 公共函数，用于获取数据并处理
async function fetchData(status) {
  curNow.value = status;
  const res = await getDaiBanAPI(status);
  if (status - 1 === 0) {
    options = [
      {
        text: '删除',
        style: {
          backgroundColor: '#dd524d'
        }
      },
      {
        text: '已完成',
        style: {
          backgroundColor: '#007aff'
        }
      }
    ]
  } else if (status - 1 === 1) {
    options = [
      {
        text: '取消',
        style: {
          backgroundColor: '#ffbb00'
        }
      }
    ]
  } else if (status - 1 === 2) {
    options = [
      {
        text: '取消',
        style: {
          backgroundColor: '#ffbb00'
        }
      }
    ]
  } else if (status - 1 === 3) {
    options = [
      {
        text: '删除',
        style: {
          backgroundColor: '#dd524d'
        }
      },
      {
        text: '已完成',
        style: {
          backgroundColor: '#007aff'
        }
      }
    ]
  }
  return res.data.map(item => ({
    ...item,
    avatar: "https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png",
    shows: true, // 默认值，可以根据实际需要进行修改
  }));
}


onShow(async () => {
  arrOne.value = await fetchData(1);
  baseForm.value.setRules(rules.value)
  console.log(arrOne.value)
})
const arrOne = ref([]);

let options = reactive([
  {
    text: '删除',
    style: {
      backgroundColor: '#dd524d'
    }
  },
  {
    text: '已完成',
    style: {
      backgroundColor: '#007aff'
    }
  }
])
const daibaninfo = ref({
  'title': '',
  'content': '',
  'status': '',
  'expectedTime': null,
  'location': '',
  'taskPriority': '',
  'flagNew': false,
})
const formValues = ref({...daibaninfo.value});

/*表单就校验*/
const rules = ref({
  // 对name字段进行必填验证
  title: {
    // name 字段的校验规则
    rules: [
      // 校验 name 不能为空
      {
        required: true,
        errorMessage: '请填写标题',
      },
      // 对name字段进行长度验证
      {
        minLength: 1,
        maxLength: 15,
        errorMessage: '{label}长度在 {minLength} 到 {maxLength} 个字符',
      }
    ],
    // 当前表单域的字段中文名，可不填写
    label: '标题',
    validateTrigger: 'submit'
  },
  content: {
    rules: [
      {
        required: true,
        errorMessage: '请填写内容',
      }
    ]
  },
  expectedTime: {
    rules: [
      {
        required: true,
        errorMessage: '请填写预计时间'
      }
    ]
  }
})

// const state = ref({
//   showSex: false,
//   radio: '',
//   switchVal: false
// })


// 使用 ref 创建响应式引用
const formRef = ref(null);

// // 定义方法，注意在 setup 中不需要 this，直接访问响应式引用
// function sectionChange(index) {
//   curNow.value = index;
// }
const baseForm = ref(null);
/*提交按钮方法*/
const submit = async () => {
  const res1 = await baseForm.value.validate();
  console.log(res1)
  console.log('提交的数据：', formValues.value);
  const res = await updateDaiBanOneAPI(formValues.value)
  console.log(res)
  if (res.code === 200) {
    // TODO
    console.log(curNow.value);
    arrOne.value = await fetchData(curNow.value);
    console.log(res);
    uToastRef.value.success(res.msg)
    showT.value = false
  } else {
    console.log(res.msg, "vadvnakljsdv")
    // 提交逻辑
    await uToastRef.value.error(res.msg)
  }
};
/*重置菜单操作*/
const reset = () => {
  formValues.value.title = '';
  formValues.value.content = '';
  formValues.value.expectedTime = null;
  formValues.value.location = '';
  formValues.value.taskPriority = '';
  formValues.value.status = '';
  formValues.value.flagNew = false;
}
// 创建对子组件的引用
const uToastRef = ref(null);
// 用于判断是否完成和删除
const dat = ref({
  id: null,
  statusId: null
});
const oncl = async (e, item, index) => {
  if (e.content.text === '已完成') {
    // arrJinXingZhong.value.splice(index, 1)
    // TODO 发送已完成请求
    dat.value.id = item.id;
    dat.value.statusId = 3;
    const res = await updateDaiBanAPI(dat.value);
    console.log(arrOne.value)
    if (res.code === 200) {
      arrOne.value[index].shows = false
      modeClass.value = 'slide-right'
      uToastRef.value.success("成功")
    }
  } else if (e.content.text === '删除') {
    // TODO 发送删除请求
    console.log(item.id)
    const res = deleteDaiBanAPI(item.id)
    res.then(async res => {
      if (res.code === 200) {
        uToastRef.value.success(res.msg)
        item.shows = false
      }
    })
    console.log(arrOne.value)
  } else if (e.content.text === '取消') {
    dat.value.id = item.id;
    dat.value.statusId = 1;
    const res = await updateDaiBanAPI(dat.value);
    if (res.code === 200) {
      item.shows = false
      modeClass.value = 'slide-right'
      uToastRef.value.success("取消成功")
    } else {
      uToastRef.value.success("取消失败")
    }
    console.log(res)
  }
  if (arrOne.value.every(item => item.shows === false)) {
    console.log('所有元素的 shows 都为 false');
    arrOne.value = []
  }
}

// 1. 创建一个格式化日期的方法
function formatDate(dateString) {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}年${month}月${day}日 ${hours}时${minutes}分${seconds}秒`;
}
</script>


<style lang="scss" scoped>
.chat-custom-right {
  flex: 1;
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-end;
}

.chat-custom-text {
  font-size: 12px;
  color: #999;
}
</style>
